﻿

#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/xfeatures2d/nonfree.hpp>


using namespace cv;
using namespace std;

int main()
{
	Mat image1 = imread("E://VC_project//figure//book//imageProcessing1.jpg");
	Mat image2 = imread("E://VC_project//figure//book//imageProcessing2.jpg");

	resize(image1, image1, Size(image1.cols / 6, image1.rows / 6));
	resize(image2, image2, Size(image2.cols / 6, image2.rows / 6));

	Mat gray1, gray2;
	cvtColor(image1, gray1, COLOR_RGB2GRAY);
	cvtColor(image2, gray2, COLOR_RGB2GRAY);

	//创建orb算子
	Ptr<ORB> orb = ORB::create();
	vector<KeyPoint> keypoints1, keypoints2;
	Mat descriptors1, descriptors2;

	////同时检测特征点和描述子向量
	orb->detectAndCompute(gray1, Mat(), keypoints1, descriptors1);
	orb->detectAndCompute(gray2, Mat(), keypoints2, descriptors2);

	/*
	BFMatcher matcher;

	vector<vector<DMatch>> matches;
	
	vector<Mat> train_desc(1, descriptors1);
	matcher.add(train_desc);
	matcher.train();

	matcher.knnMatch(descriptors2, matches, 2);

	vector<DMatch> goodMatches;
	for (int i = 0; i < matches.size(); i++)
	{
		if (matches[i][0].distance <0.7*matches[i][1].distance)
		{
			goodMatches.push_back(matches[i][0]);
		}
	}
	*/

	flann::Index flannIndex(descriptors1, flann::LshIndexParams(12, 20, 2), cvflann::FLANN_DIST_HAMMING);

    vector<DMatch> goodMatches;//保存较优匹配的特征点

    Mat macthIndex(descriptors2.rows, 2, CV_32SC1), matchDistance(descriptors2.rows, 2, CV_32FC1);
    flannIndex.knnSearch(descriptors2, macthIndex, matchDistance, 2, flann::SearchParams());

    // 获取优秀匹配点
    for (int i = 0; i < matchDistance.rows; i++)
    {
        if (matchDistance.at<float>(i,0) < 0.8 * matchDistance.at<float>(i, 1))
        {
            DMatch dmatches(i, macthIndex.at<int>(i, 0), matchDistance.at<float>(i, 0));
            goodMatches.push_back(dmatches);
        }
    }
	//画出匹配图
	Mat imageMatch;
	drawMatches(image2, keypoints2, image1, keypoints1, goodMatches, imageMatch);

	imshow("imageMatch", imageMatch);
	imwrite("imageMatch.jpg", imageMatch);
	waitKey();

}


